using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MyApp.WebApi.Entity;
using MyApp.WebApi.ParamModel;
using MyApp.WebApi.Repository;
using MyApp.WebApi.Utils;

namespace MyApp.WebApi.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IRepository<Users> _usersRespository;

        private IRepository<Shoppings> _shoppingsRespository;

        private TokenParameter _tokenParameter;

        private readonly IConfiguration _configuration;

        public UsersController(
            IConfiguration configuration,
            IRepository<Users> usersRespository,
            IRepository<Shoppings> shoppingsRespository
        )
        {
            _configuration = configuration;
            _usersRespository = usersRespository;
            _shoppingsRespository = shoppingsRespository;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }

        //分页
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {
            //get请求默认从uri从获取参数，所以此处应该加上FromQuery的特性才能正确获得参数
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;
            var rowsTotal = pager.RowsTotal;

            // 获得所有满足条件的记录
            var users =
                _usersRespository.Table.Where(x => x.IsDeleted == false);

            //   var users = from user in _usersRespository.Table
            //         join comments in _commentRespository.Table on user.Id equals comments.UserId

            //         join usersmanagement in _usermanagementRespository.Table on user.Id equals usersmanagement.UserId
            //         join like in _likeRespository.Table on user.Id equals like.UserId
            //         join article in _articleRespository.Table on user.Id equals article.UserId
            //         orderby user.Id
            //         select new
            //         {
            //             Id = user.Id,
            //             Username = user.Username,
            //             Password = user.Password,
            //             IsActived = user.IsActived,
            //             IsDeleted = user.IsDeleted,
            //             IsManagement=user.IsManagement,
            //             CreatedTime = user.CreatedTime,
            //             Remarks = user.Remarks
            //         };
            // 对获得的记录分页
            var u =
                users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res =
                new {
                    Code = 1000,
                    Data =
                        new {
                            Data = u,
                            Pager =
                                new {
                                    pageIndex,
                                    pageSize,
                                    rowsTotal = users.Count()
                                }
                        },
                    Msg = "获取用户列表成功^_^"
                };
            return res;
        }

        //获取用户列表
        [HttpGet, Route("getlist")]
        public dynamic GetList()
        {
            var list = _usersRespository.Table.ToList();
            return list;
        }

        //获取指定用户
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRespository.GetById(id);

            if (user == null)
            {
                return new { Code = 1000, Data = "", Msg = "指定用户不存在" };
            }
            return new {
                Code = 1000,
                Data = user,
                Msg = "获取用户列表成功^_^"
            };
        }

        //添加用户
        [HttpPost]
        public string Post(NewUser model)
        {
            // JsonSerializerSettings settings = new JsonSerializerSettings();
            // // settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            // settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            // var shoppingsId = model.ShoppingsId;
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var remarks = model.Remarks.Trim();
            var users =
                _usersRespository
                    .Table
                    .Where(x => x.Username == username)
                    .ToList()
                    .FirstOrDefault();
            if (string.IsNullOrEmpty(username))
            {
                var tmp =
                    new {
                        Code = 1004,
                        Data = "",
                        Msg = "用户名不能为空，请确认后重试"
                    };
                return JsonHelper.Serialize(tmp);
            }
            else
            {
                if (users != null)
                {
                    return JsonHelper
                        .Serialize(new {
                            Code = 400,
                            Data = "",
                            Msg = "该用户已存在"
                        });
                }
                else
                {
                    Shoppings shoppings = new Shoppings
                    {
                        Number = 0,
                        Price = 0,
                        Sum = 0
                    };

                    _shoppingsRespository.Insert(shoppings);


                    var user =
                        new Users {
                            Shopping = shoppings,
                            Username = username,
                            Password = password,
                            Remarks = remarks
                        };

                    _usersRespository.Insert (user);

                    var res =
                        new { Code = 1000, Data = user, Msg = "创建用户成功" };
                    return JsonHelper.Serialize(res);
                }
            }
        }

        //修改用户状态
        [HttpPost, Route("IsActived/{id}")]
        public dynamic IsActived(int id, NewUser model)
        {
            var user = _usersRespository.GetById(id);

            var num = model.IsActived;
            if (user != null)
            {
                if (num == false)
                {
                    user.IsActived = false;
                    user.UpdatedTime = DateTime.Now;
                    _usersRespository.Update (user);
                    return JsonHelper
                        .Serialize(new {
                            Code = 200,
                            Data = user,
                            Msg = string.Format("修改成功,{0}用户被禁用", id)
                        });
                }
                else
                {
                    user.IsActived = true;
                    user.UpdatedTime = DateTime.Now;
                    _usersRespository.Update (user);
                    return JsonHelper
                        .Serialize(new {
                            Code = 200,
                            Data = user,
                            Msg = string.Format("修改成功,{0}用户被激活", id)
                        });
                }
            }
            return JsonHelper
                .Serialize(new { Code = 104, Data = user, Msg = "修改失败" });
        }

        //是否为管理员
        [HttpPost, Route("IsManagement/{id}")]
        public dynamic IsManagement(int id, NewUser model)
        {
            var user = _usersRespository.GetById(id);
            var num = model.IsManagement;
            if (user != null)
            {
                if (num == false)
                {
                    user.IsManagement = false;
                    user.UpdatedTime = DateTime.Now;
                    _usersRespository.Update (user);
                    return JsonHelper
                        .Serialize(new {
                            Code = 200,
                            Data = user,
                            Msg =
                                string.Format("修改成功,{0}用户为普通用户", id)
                        });
                }
                else
                {
                    user.IsManagement = true;
                    user.UpdatedTime = DateTime.Now;
                    _usersRespository.Update (user);
                    return JsonHelper
                        .Serialize(new {
                            Code = 200,
                            Data = user,
                            Msg = string.Format("修改成功,{0}用户为管理员", id)
                        });
                }
            }
            return JsonHelper
                .Serialize(new { Code = 104, Data = user, Msg = "修改失败" });
        }

        //修改用户信息
        [HttpPut("{id}")]
        public dynamic Put(int id, NewUser model)
        {
            var user = _usersRespository.GetById(id);

            if (user != null)
            {
                user.Username = model.Username;
                user.Password = model.Password;
                user.Remarks = model.Remarks;
                user.UpdatedTime = DateTime.Now;

                // user.IsDeleted=false;
                // user.IsActived = model.state;
                _usersRespository.Update (user);
                return JsonHelper
                    .Serialize(new {
                        Code = 1000,
                        Data = user,
                        Msg =
                            string
                                .Format("你修改的用户的id为：{0}，已经修改成功，请注意查收",
                                id)
                    });
            }
            else
            {
                return JsonHelper
                    .Serialize(new {
                        Code = 104,
                        Data = "",
                        Msg = "指定Id的用户不存在，请确认后重试"
                    });
            }
        }

        //删除
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var user = _usersRespository.GetById(id);
            if (user != null)
            {
                // _usersRespository.Delete (id);
                user.IsDeleted = true;

                return new {
                    Code = 1000,
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                };
            }
            else
            {
                return new {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                };
            }
        }

        [AllowAnonymous]
        // 注册
        [HttpPost, Route("register")]
        public dynamic register(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var tryPassword = model.tryPassword.Trim();
            var users =
                _usersRespository
                    .Table
                    .Where(x => x.Username == username)
                    .ToList()
                    .FirstOrDefault();
            if (
                username.Length > 0 &&
                password.Length > 0 &&
                tryPassword.Length > 0 &&
                password == tryPassword
            )
            {
                if (users != null)
                {
                    return new { Code = 400, Data = "", Msg = "该用户已存在" };
                }
                else
                {
                    var user =
                        new Users { Username = username, Password = password };
                    _usersRespository.Insert (user);
                    return JsonHelper
                        .Serialize(new {
                            Code = 1000,
                            Data = user,
                            Msg = "用户注册成功"
                        });
                }
            }
            else
            {
                return JsonHelper
                    .Serialize(new {
                        Code = 1004,
                        Data = "",
                        Msg =
                            "用户名、密码和确认密码不能为空，且两次密码应该一致"
                    });
            }
        }

        //登录
        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();

            var user =
                _usersRespository
                    .Table
                    .Where(x =>
                        x.Username == username && x.Password == password)
                    .FirstOrDefault();

            if (user == null)
            {
                return new {
                    Code = 1001,
                    Data = user,
                    Msg = "用户名或密码不正确，请核对后重试"
                };
            }
            else
            {
                if (user.IsDeleted == false)
                {
                    if (user.IsActived == true)
                    {
                        var token =
                            TokenHelper.GenerateToekn(_tokenParameter, user);
                        var refreshToken = "123456";

                        var res =
                            new {
                                Code = 1000,
                                Data =
                                    new {
                                        Token = token,
                                        RefreshToken = refreshToken
                                    },
                                Msg = "用户登录成功，获取token成功"
                            };
                        return res;
                    }
                    else
                    {
                        return new {
                            Code = 1001,
                            Data = user,
                            Msg = "用户已禁用"
                        };
                    }
                }
                else
                {
                    return new { Code = 1001, Data = user, Msg = "用户已删除" };
                }
            }
        }
    }
}
